package wechat

import (
	"fmt"
	"tms-server/env"
	"tms-server/utils"
)

type (
	config struct {
		appID  string
		secret string
	}
	Code2sessionInfo struct {
		OpenID     string `json:"openid"`
		SessionKey string `json:"session_key"`
		Uinionid   string `json:"uinionid"`
		Errcode    int    `json:"errcode"`
		ErrMsg     string `json:"errMsg"`
	}
)

var (
	conf config
)

func Init(appID, secret string) {
	conf.appID = appID
	conf.secret = secret
}

func GetOpenID(code string) (res *Code2sessionInfo, err error) {
	if env.Runmode == env.RunModeDev {

	}
	uri := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", conf.appID, conf.secret, code)
	utils.Info(uri)
	res = new(Code2sessionInfo)
	err = utils.RequestGET(uri, res)
	if err != nil {
		return
	}
	if res.Errcode != 0 {
		err = fmt.Errorf("请求失败，errcode:%d,errInfo:%s", res.Errcode, res.ErrMsg)
		return
	}
	return
}
